package com.Policing.CanniBalize;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.Policing.Adapter.Input_Adapter_item;
import com.Policing.BaseActivity;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Receive.add_admin;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.Shift.Allot_unit;
import com.Policing.Since_case.Since_case;
import com.Policing.bean.Input_item;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnDismissListener;
import com.bigkoo.alertview.OnItemClickListener;

import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CanniBalize_add extends BaseActivity implements OnDismissListener {
    private ImageView fh;
    private List<String> assetId = new ArrayList<>();//资产id
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private TextView title_text,admin_tv,fold_section;
    private String id,name,admin_id="",fold_unit_id="";//admin——id管理员id，单位id。位置id
    private EditText allot_remark,et_num;
    private Button up_bt,scan_img;//上传数据，扫码
    private LinearLayout admin_ly,fold_unit;
    private CanniBalize_add content;
    private String url ="http://"+ Ip_Set.IP+"/api/assetScanAllotQuery";//获取资产信息url
    private String url_up ="http://"+ Ip_Set.IP+"/api/allotAdd";//上传
    private List<Input_item> data = new ArrayList<>();//扫码
    private Handler handler = new Handler();
    private ListView lv_list;
    @Override
    public int intiLayout() {
        return R.layout.cannibalize_add;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences mm = getSharedPreferences("mm", Context.MODE_PRIVATE);//1.通过上下文得到
        id = mm.getString("id","");
        name = mm.getString("name","");
        content = this;
        admin_id = id;
    }

    @Override
    public void initView() {
        et_num = (EditText) findViewById(R.id.et_num);
        et_num.setInputType(InputType.TYPE_NULL);
        up_bt = (Button) findViewById(R.id.allot_upload);
        scan_img = (Button) findViewById(R.id.scan_img);
        allot_remark = (EditText) findViewById(R.id.allot_remark);
        admin_ly = (LinearLayout)findViewById(R.id.admin_ly);
        admin_tv = (TextView)findViewById(R.id.admin_tv);
        fh = (ImageView) findViewById(R.id.fh);
         title_text  = (TextView) findViewById(R.id.title_text);
        fold_section = (TextView) findViewById(R.id.fold_section);
        fold_unit = (LinearLayout) findViewById(R.id.fold_unit);
        lv_list = (ListView) findViewById(R.id.fragment2_list);

    }

    @Override
    public void initData() {
        admin_tv.setText(name);
        title_text.setText("添加调拨单");
        admin_ly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(content, add_admin.class);
                startActivityForResult(intent,7);
            }
        });
        lv_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int i, long id) {
                new AlertView(" 提示！", "是否删除", "取消",new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){

                            for (int j=0;j<lv_data.size();j++){
                                if (lv_data.get(j).equals(data.get(i).getCode_number())){
                                    lv_data.remove(j);
                                }
                            }
                            data.remove(i);
                            Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                            lv_list.setAdapter(adapter_item);
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(content).show();
            }
        });
        et_num.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et_num.selectAll();
            }
        });
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i=0;i<data.size();i++){
                    if (et_num.getText().toString().trim().equals(data.get(i).getCode_number())){
                        Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                if (!et_num.getText().toString().trim().equals("")){
                    if (!lv_data.contains(et_num.getText().toString().trim())){
                        post(et_num.getText().toString().trim(),"");
                    }else {
                        Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
                    }

                }else {
                    Toast.makeText(content,"错误的格式",Toast.LENGTH_SHORT).show();
                }
            }
        });
    fh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
       fold_unit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent dept = new Intent(content, Allot_unit.class);
                dept.putExtra("status","2");
                startActivityForResult(dept, 1);
            }
        });

        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        up_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (data.size()<=0){
                    Toast.makeText(content,"请扫码需要调拨的资产",Toast.LENGTH_SHORT).show();
                    return;
                }

                if (fold_unit_id.equals("")){
                    Toast.makeText(content,"请完善数据",Toast.LENGTH_SHORT).show();
                    return;
                }
                new AlertView(" 提示！", "是否上传数据", "取消",new String[]{"确定"}, null, content, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position==0){
                            assetId.clear();
                            for (int i =0;i<data.size();i++){
                                assetId.add(data.get(i).getCode_number());
                            }
                             upload();
                        }
                        if (position==-1){

                        }

                    }
                }).setCancelable(true).setOnDismissListener(content).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode==7&&resultCode==7){
            admin_tv.setText(datas.getExtras().getString("admin_name"));
            admin_id = datas.getExtras().getString("admin_id");
        }
        if (requestCode==1&&resultCode==1){
            fold_unit_id = datas.getExtras().getString("dept_id");
            String name = datas.getExtras().getString("dept_name");
            fold_section.setText(name);

        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            if (!lv_data.contains(scanResult)){
                post(scanResult,"");
            }else Toast.makeText(content,"该资产已存在列表",Toast.LENGTH_SHORT).show();
        }
    }
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(content, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(content, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(content, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(content, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
    private void post(final String assetNumber, final String rfid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("assetNumber",assetNumber)
                        .add("source", Since_case.set().getSource())
                        .add("rfid",rfid);
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.i("123123", responseData);
                                    Bitmap bitmap =null;
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("state").equals("1")){
                                        lv_data.add(assetNumber);
                                        JSONObject json = jsonObject.getJSONObject("asset");
                                       // String assetName = json.getString("assetName");
                                        String deptId = json.getString("deptId");
                                        String assetNumber = json.getString("assetNumber");
                                        String userId = json.getString("userId");
                                        String model = json.getString("model");
                                        String type = json.getString("type");
                                        String place = json.getString("placeId");
                                        if (json.getString("image").equals("")){
                                            /*InputStream is = getResources().openRawResource(R.mipmap.null_po);
                                            bitmap = BitmapFactory.decodeStream(is);*/
                                        }else {
                                            byte [] input = Base64.decode(json.getString("image"), Base64.DEFAULT);
                                            bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                                        }
                                        Collections.reverse(data);
                                        data.add(new Input_item(bitmap,type,deptId,assetNumber,userId,model,place,""));
                                        Collections.reverse(data);
                                        Input_Adapter_item adapter_item = new Input_Adapter_item(content,R.layout.input_adapter_item,data);
                                        lv_list.setAdapter(adapter_item);
                                        Toast.makeText(content,"添加成功",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("0")){
                                        Toast.makeText(content,"失败",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("2")){
                                        Toast.makeText(content,"资产不存在",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("3")){
                                        Toast.makeText(content,"当前资产不可调拨",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        });

                    }
                });

            }
        }).start();
    }

    @Override
    public void onDismiss(Object o) {

    }
    private void upload() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
                FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
                formBody.add("inunit","")
                        .add("id",id)
                        .add("source",Since_case.set().getSource())
                        .add("inuser",admin_id)
                        .add("indept",fold_unit_id)
                        .add("assetNumbers", String.valueOf(assetId))
                        .add("remark",allot_remark.getText().toString()); //传递键值对参数
                Request request = new Request.Builder()//创建Request 对象。
                        .url(url_up)
                        .post(formBody.build())//传递请求体
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //回调方法的使用与get异步请求相同
                        Log.i("123123", "error");
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String responseData = response.body().string();
                        //回调方法的使用与get异步请求相同
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.i("123123", responseData);
                                    JSONObject jsonObject = new JSONObject(responseData);
                                    if (jsonObject.getString("state").equals("1")){
                                        finish();
                                        Toast.makeText(content,"提交成功",Toast.LENGTH_SHORT).show();
                                    }
                                    if (jsonObject.getString("state").equals("0")){
                                        Toast.makeText(content,"提交失败",Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }
                        });

                    }
                });

            }
        }).start();
    }
}
